package com.tuantuan.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tuantuan.dao.CommenDao;
import com.tuantuan.dao.UsersDao;
import com.tuantuan.model.Teachers;
import com.tuantuan.model.Users;
import com.tuantuan.service.CommenService;

@Service("TeacherService")
@Transactional
public class TeacherServiceImpl implements CommenService<Teachers>{

	@Resource(name="TeacherDao")
	private CommenDao<Teachers> teach;
	@Resource(name="UsersDao")
	private UsersDao usersDao;
	/**
	 * 新增教师时同时新增类型为教师的用户，账号密码同为教师号
	 */
	@Override
	public String addEntity(Teachers entity) {
		// TODO Auto-generated method stub
		Teachers tt = teach.queryByCode(entity);
		if(tt == null){
			entity.setPassword(entity.getTcno());
			
			Users u = new Users();
			u.setUserAccount(entity.getTcno());
			u.setPassword(entity.getTcno());
			u.setUserType(3);
			u.setPhone(entity.getPhone());
			u.setEmail(entity.getEmail());
			teach.addEntity(entity);
			usersDao.addUser(u);
			return "succ";
		}
		return "fail";
	}

	/**
	 * 删除教师信息（联动删除用户信息）
	 */
	@Override
	public String deleteEntity(int entityId) {
		// TODO Auto-generated method stub
		Teachers t = new Teachers();
		t.setTcId(entityId);
		Teachers tt = teach.queryById(t);
		if(tt != null){
			Users u = new Users();
			u.setUserAccount(tt.getTcno());
			usersDao.deleteUser(u);
			teach.deleteEntity(tt);
			return "succ";
		}
		return "fail";
	}

	/**
	 * 更新教师信息（联动更新用户信息（在修改了教师编号的时候））
	 */
	@Override
	public String updateEntity(Teachers entity) {
		// TODO Auto-generated method stub
		Teachers tt = teach.queryByCode(entity);
		if(tt == null){
			Teachers teaOld = teach.queryById(entity);
			if(!teaOld.getTcno().equals(entity.getTcno())){
				Users u1 = new Users();
				u1.setUserAccount(teaOld.getTcno());
				Users u = usersDao.queryUserByCode(u1);
				u.setUserAccount(entity.getTcno());
				u.setPassword(entity.getTcno());
				usersDao.updateUserBystu(u);
			}
			teach.updateEntity(entity);
			return "succ";
		}
		return "fail";
	}

	public CommenDao<Teachers> getTeach() {
		return teach;
	}

	public void setTeach(CommenDao<Teachers> teach) {
		this.teach = teach;
	}

	
}
